#include <stdio.h>
#include <unistd.h>

#include <coap2/coap.h>


#include "coap-client.h"


int main ()
{
  int count = 0;

  coap_log_t log_level = LOG_INFO;
  coap_set_log_level(log_level);

  const char *host = "192.168.244.112";
  const char* port = "5683";

  
  while (!coap_signal_state()) {

    char* data = "coap from jc@";

    /* The listen is true the listen status must be true
       then into initial connection
      if listen is false the listen status may be false or true
    */
    /* 
      listen: true, listen_server_status: true
      listen: false 
              1. listen_server_status: true (already initial)
              2. listen_server_status: false
    */
    unsigned short listen = listen_connect_server(host, port);
    unsigned short* status = check_server_active_status();
    unsigned short ready = 
        ((*status && !listen)) ? 0 : 
         ((*status && !listen) || (listen && *status)) ? 1 : 0;

    printf("read:%d status:%d listen:%d\n", ready, *status, listen);
    if (ready) {
      release_session();
      if (init_global_uri((char*)host, "5683", "data") != 0) {
        coap_log(LOG_ERR, "init global uri failure\n");
        return 0;
      } else
        coap_log(LOG_INFO, "init global uri successful\n");

      if (create_session() != 0) {
        coap_log(LOG_ERR, "create session failure\n");
        return 0;
      } else
        coap_log(LOG_INFO, "create session successful\n");
      }

    if (*status) {
      if (once_send_message(COAP_REQUEST_PUT, 9* 100, data, strlen(data)) < 0) {
        coap_log(LOG_ERR, "once send coap message failed\n");
         /* retry listen server */
        *status = 0;
        release_session();
        // return -1;
      } else
        coap_log(LOG_INFO, "once send coap message successful\n");
    }

  usleep(20 * 1000);
  }
}